/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.toools.gwt.wmc.server.dao.toplink;

import java.util.Collection;
import javax.persistence.NoResultException;
import oracle.toplink.essentials.expressions.Expression;
import oracle.toplink.essentials.expressions.ExpressionBuilder;
import oracle.toplink.essentials.ejb.cmp3.EntityManager;
import org.springframework.stereotype.Repository;
import org.toools.gwt.wmc.server.dao.IApplicationDAO;
import org.toools.gwt.wmc.jpa.Application;

/**
 *
 * @author ich
 */
@Repository
public class ApplicationDAO implements IApplicationDAO{

//    private EntityManager em;
//
//    @PersistenceContext
//    public void setEntityManager( EntityManager em ) {
//        this.em = em;
//    }

    public Application getApplicationByID(Integer id) {
        Application result;
        try {
            result = (Application) EMFKeeper.EM.createNamedQuery("Application.getById").setParameter("id", id).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
        System.out.println("fetched application " + result.getId() + " from db.");
        return result;
    }

    public Boolean belongsTo( Integer id, Integer accountid ) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public Collection<Application> getApplications() {
        Collection<Application> ret = EMFKeeper.EM.createNamedQuery("Application.getAll").getResultList();

        System.out.println("fetched " + ret.size() + " applications from db.");
        return ret;
    }

    public Collection<Application> getApplications(Integer accountid) {
        EntityManager em = (EntityManager)EMFKeeper.EM;

        ExpressionBuilder eb = new ExpressionBuilder();
        Expression accadditives = eb.anyOf( "companyParts" ).anyOf( "companie" ).get( "account" ).get( "id" ).equal( accountid );

        Collection<Application> ret = em.getSession().readAllObjects( Application.class, accadditives );
        return ret;
    }

    public Application create(Application a) {
        return SimpleCUD.create( a );
    }

    public Boolean delete(Application a) {
        Application rem = (Application) EMFKeeper.EM.createNamedQuery( "Application.getById" ).setParameter( "id", a.getId() ).getSingleResult();
        return SimpleCUD.delete( rem );
    }

    public Boolean update(Application a) {
        return SimpleCUD.update( a );
    }
}
